<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/14
 * Time: 14:22
 * 优惠券
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\RebateRecord;
use think\Db;

class Coupon extends Api {
	
	protected $noNeedLogin = ['index', 'getcategory'];
	protected $noNeedRight = '*';
	
	public function index(){
		$model = new RebateRecord();
		$rows = Db::name('rebateRecord')->alias('r')
			->join('user u', 'r.user_id = u.id', 'left')
			->where(['r.status' => $model::STATUS_Y])
			->order(['r.update_time' => 'DESC'])
			->limit(10)
			->field('u.mobile, r.amount, from_unixtime(create_time) as time')
			->select();
		if($rows) {
			foreach($rows as $k => $v) {
				$rows[$k]['mobile'] = substr($v['mobile'],0,3).'****'.substr($v['mobile'],7, 11);
			}
		}
		$this->success('查询成功', $rows);
	}
	
	/**
	 * 兑换优惠券
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function exchange(){
		$data = input('post.');
		if(in_array($data['goods_type'], ['tbk', 'tmall', 'taobao'])){
			$data['goods_type'] = 'tbk';
		}
		
		switch ($data['goods_type']) {
			case 'tbk':
				$obj = new Tbk();
				$res = $obj->taobaoTbkTpwdCreate($data['goods_title'], $data['coupon_click_url']?:$data['item_url'], $data['goods_img']);
				$tkl = isset($res['data']['model']) ? $res['data']['model']: '';
				$res = $obj->exchange($data['goods_id'], $data['coupon_amount']);
				if(!$res) {
					$this->error($res['info']);
				}
				$returnData = [
					'coupon_url' => $data['coupon_click_url'] ? : '',
					'goods_url' => $data['coupon_click_url'] ? $data['coupon_click_url'] : $data['item_url'],
					'tkl' => $tkl
				];
				$this->success('兑换成功', $returnData);
				break;
			case 'jd':
				$obj = new Jd();
				$res = $obj->exchangeCoupon($data);
				
				if(!$res['status']) {
					$this->error($res['info']);
				}
				
				$this->success('兑换成功', $res['info']);
				break;
			case 'pdd':
				$obj = new Pdd();
				$res = $obj->exchange($data['goods_id'], $data['coupon_amount']);
				if(!$res) {
					$this->error($res['info']);
				}
				
				$returnData = [
					'info' => $res['info'],
					'coupon_url' => $res['info']['mobile_short_url'],
					'goods_url' => $res['info']['mobile_short_url']
				];
				$this->success('兑换成功', $returnData);
				break;
			default:
				$this->error('类型错误');
		}
	}
	
	
	/**
	 * 分类
	 */
	public function getCategory(){
		$pid = input('post.pid', 0, 'intval');
		$rows = Db::name('couponCategory')
			->order(['sort' => 'ASC'])
			->where(['parent_id' => $pid])
			->field('id, name, image')
			->select();
		$this->success('查询成功', $rows);
	}
	
}